<template>
  <el-dialog class="assign-role" title="分配角色" :visible="showRoleDialog" @close="closeDialog" @open="dialogOpen">
    <!-- el-checkbox-group选中的是 当前用户所拥有的角色  需要绑定 当前用户拥有的角色-->
    <el-checkbox-group v-model="roleIds" :loading="loading">
      <!-- 特例：复选框非常特殊，通过label收集选中的值，控制选中状态，
           一般复选框label中绑定的就是提交给后台的id -->
      <!-- <el-checkbox label="101">人事</el-checkbox> -->
      <el-checkbox v-for="item in list" :key="item.id" :label="item.id">
        {{ item.name }}
      </el-checkbox>
    </el-checkbox-group>

    <template #footer>
      <div style="text-align: right">
        <el-button type="primary" @click="clickSubmit">确定</el-button>
        <el-button @click="closeDialog">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { reqGetRoleList } from '@/api/setting'
import { reqGetAvatar } from '@/api/user'
import { reqAssignRoles } from '@/api/employees'
export default {
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    },
    // 用户的id 用来查询当前用户的角色信息
    userId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      list: [],
      roleIds: [],
      loading: false
    }
  },

  methods: {
    closeDialog() {
      this.$emit('update:showRoleDialog', false)
      this.roleIds = []
    },
    async getRoleList() {
      const { data: res } = await reqGetRoleList(1, 100)
      this.list = res.rows
    },
    async getUserDetail() {
      const { data: res } = await reqGetAvatar(this.userId)
      this.roleIds = res.roleIds
    },
    async clickSubmit() {
      const data = {
        id: this.userId,
        roleIds: this.roleIds
      }
      const res = await reqAssignRoles(data)
      this.$message.success(res.message)
      this.closeDialog()
    },
    dialogOpen() {
      this.loading = true
      Promise.all([this.getRoleList(), this.getUserDetail()]).then(values => {
        this.loading = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.assign-role {
  ::v-deep {
    .el-checkbox {
      font-size: 30px;
    }
  }
}
</style>
